import 'package:flutter/material.dart';
import 'package:toast/toast.dart';
import 'package:peach/config/_.dart';
import 'package:peach/service/_.dart';
import 'package:peach/utils/_.dart';
import 'package:peach/entity/_.dart';
import 'package:peach/widget/_.dart';

class Search extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _Search();
}

class _Search extends State<Search> {

  // 搜索框控制器
  TextEditingController _controller = TextEditingController();
  FocusNode _userFocusNode = FocusNode();

  // 搜索建议
  List<String> proposalList = [
    'JK制服','医生','豹纹','清纯','空姐','大胸','黑丝','美腿','主播','香车','教室','学生装','老师', '风骚','蜜桃社','秀人网'
  ];

  List<ItemList> result = [];

  @override
  void initState() {
    _controller.addListener(() {});
    // 监听输入框是否获得焦点，动态返回页面
    _userFocusNode.addListener(() {
      SearchProposal();
      setState(() => {});
    });
  }

  // 顶部搜索输入框
  Widget SearchItem () {
    return Container(
      height: Screen.setHeight(30.0),
      alignment: Alignment.center,
      decoration: BoxDecoration(
        color: ColorConfig.WhiteBackColor,
        borderRadius: BorderRadius.all(Radius.circular(25.0)),
      ),
      child: TextField(
        controller: _controller,
        focusNode: _userFocusNode,
        autofocus: true,
        showCursor: true,
        cursorWidth: 2,
        style: TextStyle(fontSize: 14),
        cursorRadius: Radius.circular(10),
        cursorColor: ColorConfig.ThemeColor,
        textInputAction: TextInputAction.search,
        onSubmitted: (String val) {
          GetSearchData();
        },
        decoration: InputDecoration(
          isDense: true,
          border: InputBorder.none,
          contentPadding: EdgeInsets.only(left: 15),
          hintText: '输入搜索关键字',
          hintStyle: TextStyle(color: ColorConfig.NoActiveColor,fontSize: 14),
        ),
      ),
    );
  }

  // 顶部右侧的搜索按钮
  Widget SearchButton() {
    return IconButton(
      icon: Icon(Icons.search, color: ColorConfig.WhiteBackColor,),
      onPressed: () {
        GetSearchData();
      },
    );
  }
  
  // 如果输入框获得了焦点，那么返回搜索建议，否则返回搜索列表
  Widget SearchProposal() {
    if (_userFocusNode.hasFocus) {
      return Container(
        padding: EdgeInsets.all(15),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text("搜索建议",style: TextStyle(fontWeight: FontWeight.w500,fontSize: Screen.setFontSize(15)),),
            SizedBox(height: Screen.setHeight(10),),
            Wrap(
              children: proposalList.map((e) => InkWell(
                onTap: () {
                  _controller.text = e;
                  GetSearchData();
                },
                child: Container(
                  margin: EdgeInsets.only(bottom: Screen.setFontSize(5),right: Screen.setFontSize(5)),
                  decoration: BoxDecoration(
                    color: ColorConfig.ThemeColor,
                    borderRadius: BorderRadius.all(Radius.circular(25.0)),
                  ),
                  padding: EdgeInsets.only(left: Screen.setFontSize(8),right: Screen.setFontSize(8),bottom: Screen.setFontSize(3),top: Screen.setFontSize(2)),
                  child: Text(e, style: TextStyle(color: ColorConfig.WhiteBackColor,fontSize: Screen.setFontSize(12)),),
                ),
              )).toList(),
            )
          ],
        ),
      );
    }else{
      return ItemWidget(
          data: result,
          title: '',
          longPress: () {}
      );
    }
  }

  // 如果输入框不为空，那么输入框失去焦点并关闭键盘展示搜索列表页面
  GetSearchData() async {
    if (_controller.text.length != 0) {
      _userFocusNode.unfocus();
      List<ItemList> res = await HomeService.GetSearchData(params: { "keyword": _controller.text });
      setState(() => result = res);
    } else {
      FocusScope.of(context).requestFocus(_userFocusNode);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        titleSpacing: 0.0,
        title: SearchItem(),
        elevation: 0,
        backgroundColor: ColorConfig.ThemeColor,
        actions: [ SearchButton() ],
      ),
      body: SearchProposal(),
    );
  }

  @override
  dispose() {
    super.dispose();
    _controller.dispose();
    _userFocusNode.dispose();
  }
}